const axios = require("axios");
const express = require("express");
const COS = require("cos-nodejs-sdk-v5");
const router = express.Router();
const md5 = require("md5");
const cos = new COS({
  // 移除AppId
  // AppId: process.env.COS_APP_ID,
  SecretId: process.env.COS_SECRET_ID,
  SecretKey: process.env.COS_SECRET_KEY,
});

router.post("/uploadCos", async (req, res) => {
  try {
    const { url } = req.body;

    // 从URL中提取基本文件名和扩展名
    const urlWithoutParams = url.split("?")[0];
    const fileExtension = urlWithoutParams.split(".").pop();

    // 使用MD5加密原图片URL生成文件名
    const hashedFileName = md5(url);
    const fileName = `${hashedFileName}.${fileExtension}`;

    // 下载图片
    const response = await axios.get(url, { responseType: "arraybuffer" });
    const buffer = Buffer.from(response.data, "binary");

    // 上传到腾讯云 COS
    const result = await cos.putObject({
      Bucket: process.env.COS_BUCKET,
      Region: process.env.COS_REGION,
      Key: fileName,
      Body: buffer,
    });

    // 构建上传成功的 URL
    let uploadedUrl = `${process.env.COS_CDN}/${fileName}`;
    res.json({ success: true, url: uploadedUrl });
  } catch (error) {
    console.error("上传失败:", error);
    res.status(500).json({ success: false, error: "上传失败" });
  }
});

module.exports = router;
